package com.example.zzx.dovebook.location

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.MenuItem
import androidx.appcompat.widget.SearchView
import androidx.core.content.ContextCompat
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.example.baselibrary.commonutil.Logger
import com.example.baselibrary.widget.LoadingStateView
import com.example.library.BaseAdapter
import com.example.zzx.dovebook.R
import com.example.zzx.dovebook.base.BaseActivity
import com.example.zzx.dovebook.base.BaseViewModel
import kotlinx.android.synthetic.main.activity_location.*

class LocationActivity: BaseActivity<BaseViewModel<Any>>() {

    private lateinit var emptyView: LoadingStateView
    private lateinit var loadMoreView: LoadingStateView

    private lateinit var adapter: BaseAdapter

    private var currentPage = 0
    private var currentLocationKeyword = ""

    private var areaLatLon: LatLonPoint? = null
    private var initKeyword: String? = ""

    override fun getLayoutId(): Int {
        return R.layout.activity_location
    }

    override fun createViewModel(): Class<BaseViewModel<Any>>? {
        return null
    }

    override fun initViews(savedInstanceState: Bundle?) {
        Logger.e(TAG, "initViews -> ")
        setupRecyclerView()
        setupToolbar()
    }

    override fun initIntent(savedInstanceState: Bundle?) {
        super.initIntent(savedInstanceState)
        intent?.apply {
            areaLatLon = getParcelableExtra(getString(R.string.lat_lng_point_arg_name))
            initKeyword = getStringExtra(getString(R.string.location_keyword_arg_name))
        }
    }

    private fun setupRecyclerView() {
        emptyView = LoadingStateView(this)
        emptyView.setTextColor(ContextCompat.getColor(this, R.color.support_text))
        emptyView.setOnRetryListener {
            emptyView.loading()
            queryLocation()
        }
        emptyView.empty()
        loadMoreView = LoadingStateView(this)
        loadMoreView.setTextColor(Color.TRANSPARENT)
        loadMoreView.setOnRetryListener {
            loadMoreView.loading()
            queryLocation()
        }
        adapter = BaseAdapter.Builder().emptyView(emptyView).addRooter(loadMoreView).autoLoadMore().build()
        adapter.emptyState()
        adapter.setOnLoadMoreListener {
            Logger.e(TAG, "setupRecyclerView -> load more")
            if (adapter.isInEmptyState) {
                return@setOnLoadMoreListener
            }
            loadMoreView.loading()
            queryLocation()
        }
        recyclerView.adapter = adapter
    }

    private fun setupToolbar() {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        searchView.apply {
            queryHint = getString(R.string.hint_location_search)
            isIconified = false
            onActionViewExpanded()
            val searchTextView = findViewById<SearchView.SearchAutoComplete>(R.id.search_src_text)
            searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener {
                override fun onQueryTextSubmit(p0: String?): Boolean {
                    return true
                }

                override fun onQueryTextChange(text: String): Boolean {
                    if (!TextUtils.isEmpty(text)) {
                        currentPage = 0
                        currentLocationKeyword = text
                        emptyView.loading()
                        loadMoreView.loading()
                        adapter.emptyState()
                        adapter.clearData()
                        queryLocation()
                    }
                    return true
                }

            })
            if (!TextUtils.isEmpty(initKeyword)) {
                searchTextView.setText(initKeyword)
            }
        }
    }

    private fun queryLocation() {
        Logger.e(TAG, "queryLocation -> start search")
        val query = PoiSearch.Query(currentLocationKeyword, "住宅", "")
        query.pageNum = currentPage++
        query.pageSize = 20
        val poiSearch = PoiSearch(this, query)
        areaLatLon?.let {
            poiSearch.bound = PoiSearch.SearchBound(areaLatLon, 1000)
        }
        poiSearch.setOnPoiSearchListener(object: PoiSearch.OnPoiSearchListener {
            override fun onPoiItemSearched(p0: PoiItem?, p1: Int) {

            }

            override fun onPoiSearched(result: PoiResult?, resultCode: Int) {
                result?.pois?.apply {
                    if (resultCode != 1000) {
                        Logger.e(TAG, "onPoiSearched -> result code is not 1000")
                        if (adapter.dataCount == 0) {
                            emptyView.failed()
                        } else {
                            loadMoreView.failed()
                        }
                        return
                    }
                    if (size == 0) {
                        if (adapter.dataCount == 0) {
                            emptyView.empty()
                            return@apply
                        }
                    }
                    if (adapter.isInEmptyState) adapter.cancelEmptyState()
                    if (!emptyView.isSuccess) {
                        emptyView.success()
                    }
                    if (size < 20) {
                        loadMoreView.noMore()
                    }
                    val locationList = mutableListOf<Location>()
                    for (poiItem in this) {
                        locationList.add(Location(poiItem))
                    }
                    adapter.add(locationList)
                }
            }

        })
        poiSearch.searchPOIAsyn()
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
       Logger.e(TAG, "onOptionsItemSelected -> ")
        when (item.itemId) {
            android.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }

    fun returnWithLocation(poiItem: PoiItem) {
        val result = Intent()
        result.putExtra(getString(R.string.result_location_arg_name), poiItem)
        setResult(RESULT_OK, result)
        finish()
    }
}